#include "str_buffer.h"

#include <stdlib.h>

typedef struct str_buffer{
    unsigned int size;
    unsigned int capacity;
    char *str_buf;
}str_buffer;

str_buffer *create_buffer(unsigned int size)
{
    str_buffer *p = (str_buffer *)malloc(sizeof(str_buffer));
    
    if (p) {
        p->str_buf = (char *)malloc(sizeof(char) * size);
        
        if (p->str_buf) {
            p->size = 0;
            p->capacity = size;
        }
        else {
            free(p);
            p = NULL;
        }
    }
    
    return p;
}

char *get_buffer_end(str_buffer *buf)
{
    return buf->str_buf + buf->size;
} 

void update_buffer(str_buffer *buf)
{
    const char *p = buf->str_buf + buf->size;

    while (*p != '\0') {
        ++buf->size;
        ++p;
    }
}

char *get_buffer_value(str_buffer *buf)
{
    return buf->str_buf;
}

int buffer_reserve(str_buffer *buf, unsigned int size)
{
    char *p = (char *)realloc(buf->str_buf, sizeof(char) * size);
    
    if (p) {
        buf->str_buf = p;
        buf->capacity = size;
        return 1;
    }
    else {
        return 0;
    }
}

int buffer_increase(str_buffer *buf, unsigned int increase_size)
{
    char *p = (char *)realloc(buf->str_buf, sizeof(char) * (buf->capacity + increase_size));
    
    if (p) {
        buf->str_buf = p;
        buf->capacity += increase_size;
        return 1;
    }
    else {
        return 0;
    }
}